package com.lagou.gateway.standard.formatter.minimize;

import com.alibaba.fastjson.JSONObject;
import com.lagou.gateway.BaseResponseBodyEntity;
import com.lagou.gateway.constants.JsonKeySet;
import com.lagou.gateway.standard.formatter.ResponseBodyFormatter;
import com.lagou.gateway.util.StatusCodeConvert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnProperty(value = "lagou.gateway.out.standard.formatter",havingValue = "minimize")
public class MinimizeResponseBodyFormatter extends ResponseBodyFormatter {
    private static Logger LOGGER = LoggerFactory.getLogger(MinimizeResponseBodyFormatter.class);

    @Override
    public BaseResponseBodyEntity jsonBodyFormat(HttpStatus httpStatus, JSONObject body) {
        Object data = null;
        Integer code = httpStatus.value();
        String message = null;
        try {
            for (String key :
                    body.keySet()) {
                if (JsonKeySet.keyInDataKeyNames(key)) {
                    data = body.getOrDefault(key,null);
                } else if (JsonKeySet.keyInMessageKeyNames(key)) {
                    message = body.getString(key);
                } else if (JsonKeySet.keyInCodeKeyNames(key)) {
                    code = StatusCodeConvert.convertCode(body.get(key));
                }
            }

        } catch (Exception e) {
            LOGGER.warn("Parse response body error.", e);
        } finally {
            MinimizeResponseBodyEntity entity = new MinimizeResponseBodyEntity(code, message, data);
            return entity;
        }
    }
}
